package pers.w.chaptertalk.ui.me;

import androidx.appcompat.app.AppCompatActivity;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.IReader;

import android.os.Bundle;
import android.os.Looper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

public class LeaveMessageActivity extends AppCompatActivity implements IReader {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leave_message);
        final String url = getString(R.string.server_address) + "msg.php";

        final EditText re = findViewById(R.id.et_re);
        final EditText et_msg = findViewById(R.id.et_leaveMessage);
        final Button send = findViewById(R.id.btn_leaveMessage);
        final String username = (String) Fun.SHARE_MAP.get(R.string.prompt_username);
        final String password = (String) Fun.SHARE_MAP.get(R.string.prompt_password);

        send.setOnClickListener(v -> {
            if (Fun.isNetworkConnected(this)) {

                if (username != null && password != null) {
                    String msg = et_msg.getText().toString();
                    if (msg.length() >= 5 && msg.length() <= 200) {
                        v.setEnabled(false);
                        new Thread(() -> {
                            final String encrypted = Fun.webEncrypted(username,password);
                            Connection conn = Jsoup.connect(url);
                            conn.data("msg", msg);
                            conn.data("re", re.getText().toString());
                            conn.data(ENCRYPTED,encrypted);
                            conn.data(USER, username);
                            conn.data(PASSWORD, password);
                            try {
                                Document doc = conn.post();
                                runOnUiThread(()-> Toast.makeText(this, doc.text(), Toast.LENGTH_SHORT).show());
                            } catch (IOException e) {
                                //e.printStackTrace();
                                runOnUiThread(()-> Toast.makeText(this, "发送出错", Toast.LENGTH_SHORT).show());
                            }

                        }).start();
                    } else
                        Toast.makeText(this, "最少5个字，最多200字", Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
